/**
 * @class Ext.ux.TreePicker
 * @extends Ext.form.field.Picker
 * 
 * A Picker field that contains a tree panel on its popup, enabling selection of tree nodes.
 */
Ext.define('Ext.ux.TreePicker', {
    extend: 'Ext.form.field.Picker',
    xtype: 'treepicker',

    triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger',

    config: {
        /**
         * @cfg {Ext.data.TreeStore} store
         * A tree store that the tree picker will be bound to
         */
        store: null,

        /**
         * @cfg {String} displayField
         * The field inside the model that will be used as the node's text.
         * Defaults to the default value of {@link Ext.tree.Panel}'s `displayField` configuration.
         */
        displayField: null,

        /**
         * @cfg {Array} columns
         * An optional array of columns for multi-column trees
         */
        columns: null,

        /**
         * @cfg {Boolean} selectOnTab
         * Whether the Tab key should select the currently highlighted item. Defaults to `true`.
         */
        selectOnTab: true,

        /**
         * @cfg {Number} maxPickerHeight
         * The maximum height of the tree dropdown. Defaults to 300.
         */
        maxPickerHeight: 300,

        /**
         * @cfg {Number} minPickerHeight
         * The minimum height of the tree dropdown. Defaults to 100.
         */
        minPickerHeight: 100
    },
   
    editable: false,

    initComponent: function() {
        var me = this;
        me.callParent(arguments);

        this.addEvents(
            /**
             * @event select
             * Fires when a tree node is selected
             * @param {Ext.ux.TreePicker} picker        This tree picker
             * @param {Ext.data.Model} record           The selected record
             */
            'select'
        );

        me.store.on('load', me.onLoad, me);
    },

    /**
     * Creates and returns the tree panel to be used as this field's picker.
     * @private
     */
    createPicker: function() {
        var me = this,
            picker = Ext.create('Ext.tree.Panel', {
                store: me.store,
                floating: true,
                hidden: true,
                displayField: me.displayField,
                columns: me.columns,
                 rootVisible: false,  //默认不显示根节点
                shadow: false,
                height:300,
                listeners: {
                    itemclick: Ext.bind(me.onItemClick, me)
                },
                viewConfig: {
                    listeners: {
                        render: function(view) {
                            view.getEl().on('keypress', me.onPickerKeypress, me);
                        }
                    }
                }
            }),
            view = picker.getView();

        view.on('render', me.setPickerViewStyles, me);

        if (Ext.isIE9 && Ext.isStrict) {
            // In IE9 strict mode, the tree view grows by the height of the horizontal scroll bar when the items are highlighted or unhighlighted.
            // Also when items are collapsed or expanded the height of the view is off. Forcing a repaint fixes the problem.
            view.on('highlightitem', me.repaintPickerView, me);
            view.on('unhighlightitem', me.repaintPickerView, me);
            view.on('afteritemexpand', me.repaintPickerView, me);
            view.on('afteritemcollapse', me.repaintPickerView, me);
        }
        return picker;
    },

    /**
     * Sets min/max height styles on the tree picker's view element after it is rendered.
     * @param {Ext.tree.View} view
     * @private
     */
    setPickerViewStyles: function(view) {
        view.getEl().setStyle({
            'min-height': this.minPickerHeight + 'px',
            'max-height': this.maxPickerHeight + 'px'
        });
    },

    /**
     * repaints the tree view
     */
    repaintPickerView: function() {
        var style = this.picker.getView().getEl().dom.style;

        // can't use Element.repaint because it contains a setTimeout, which results in a flicker effect
        style.display = style.display;
    },

    /**
     * Aligns the picker to the input element
     * @private
     */
    alignPicker: function() {
        var me = this,
            picker;

        if (me.isExpanded) {
            picker = me.getPicker();
            if (me.matchFieldWidth) {
                // Auto the height (it will be constrained by max height)
                picker.setWidth(me.bodyEl.getWidth());
            }
            if (picker.isFloating()) {
                me.doAlign();
            }
        }
    },

    /**
     * Handles a click even on a tree node
     * @private
     * @param {Ext.tree.View} view
     * @param {Ext.data.Model} record
     * @param {HTMLElement} node
     * @param {Number} rowIndex
     * @param {Ext.EventObject} e
     */
    onItemClick: function(view, record, node, rowIndex, e) {
        this.selectItem(record);
    },

    /**
     * Handles a keypress event on the picker element
     * @private
     * @param {Ext.EventObject} e
     * @param {HTMLElement} el
     */
    onPickerKeypress: function(e, el) {
        var key = e.getKey();

        if(key === e.ENTER || (key === e.TAB && this.selectOnTab)) {
            this.selectItem(this.picker.getSelectionModel().getSelection()[0]);
        }
    },

    /**
     * Changes the selection to a given record and closes the picker
     * @private
     * @param {Ext.data.Model} record
     */
    selectItem: function(record) {
        var me = this;
        me.setValue(record.get('id'));
        alert(record.get('id'));
        me.picker.hide();
        me.inputEl.focus();
        me.fireEvent('select', me, record)

    },

    /**
     * Runs when the picker is expanded.  Selects the appropriate tree node based on the value of the input element,
     * and focuses the picker so that keyboard navigation will work.
     * @private
     */
    onExpand: function() {
        var me = this,
            picker = me.picker,
            store = picker.store,
            value = me.value;

        if(value) {
            picker.selectPath(store.getNodeById(value).getPath());
        } else {
            picker.getSelectionModel().select(store.getRootNode());
        }

        Ext.defer(function() {
            picker.getView().focus();
        }, 1);
    },

    /**
     * Sets the specified value into the field
     * @param {Mixed} value
     * @return {Ext.ux.TreePicker} this
     */
    setValue: function(value) {
        var me = this,
            record;

        me.value = value;

        if (me.store.loading) {
            // Called while the Store is loading. Ensure it is processed by the onLoad method.
            return me;
        }
            
        // try to find a record in the store that matches the value
        record = value ? me.store.getNodeById(value) : me.store.getRootNode();

        // set the raw value to the record's display field if a record was found
        me.setRawValue(record ? record.get(this.displayField) : '');

        return me;
    },


    /**
     * Returns the current data value of the field (the idProperty of the record)
     * @return {Number}
     */
    getValue: function() {
        return this.value;
    },

    /**
     * Handles the store's load event.
     * @private
     */
    onLoad: function() {
        var value = this.value;

        if (value) {
            this.setValue(value);
        }
    }

});


Ext.onReady(function() {  
      
        Ext.QuickTips.init();  
        Ext.form.Field.prototype.msgTarget = 'side';  
        
        
        var tree_store = Ext.create('Ext.data.TreeStore', {
		    id:'tree_store',
		    proxy: {
		        type: 'ajax',
		        url: '../login/loginTree.do',
		        reader: {
		            type: 'json'
		        }
		    },
		    root: { expanded: true },//
		    autoLoad: true
		});
  		
  		var dstore = new Ext.data.JsonStore({
			proxy: new Ext.data.HttpProxy({
		     url: '../login/loginCombox.do'//相对路径
		    }),
			fields: ["name", "age"]
		});
		dstore.load();
  
        var form1 = new Ext.FormPanel({  
            collapsible: true,  
            autoHeight: true,  
            frame: true,  
            renderTo: Ext.getBody(),  
            title: '<center style="curor:hand" onclick="window.location.reload();">表单控件</center>',  
            style: 'margin-left:auto;margin-right:auto;width:500px;margin-top:8px;',  
            //设置标签对齐方式  
            labelAlign: 'right',  
            //设置标签宽  
            labelWidth: 170,  
            width:500,
            //设置按钮的对齐方式  
            buttonAlign:'center',  
            //默认元素属性设置  
            items: [{  
                fieldLabel: '文本框控件',  
                name: 'TextBox',  
                xtype: 'textfield'  
                //,readOnly : true            //只读  
                //,emptyText    :'请输入数据'    //为空时显示的文本，注意不是value  
            },{  
                fieldLabel: '只允许输入数字'  
                ,name:'TextBoxNumber'  
                ,xtype:'numberfield'  
                //,allowDecimals: false     // 允许小数点  
                //,allowNegative: false,     // 允许负数  
                //,maxValue:1000      //最大值  
                //,minValue:0            //最小值  
            },{  
                fieldLabel: '下拉框控件',  
                name: 'DropDownList',  
                xtype: 'combo',  
                //本地数据源  local/remote  
                mode:'local',  
                //设置为选项的text的字段  
                displayField: "name",         
                //设置为选项的value的字段   
                valueField: "age",  
                //是否可以输入，还是只能选择下拉框中的选项  
                editable : false,   
                typeAhead: true,  
                //必须选择一项  
                //forceSelection: true,  
                //输入部分选项内容匹配的时候显示所有的选项  
                triggerAction: 'all',  
                //selectOnFocus:true,  
                //数据  
                store:dstore
            },{  
                fieldLabel: '下拉选择树控件',  
                name: 'DropDownList2',  
                xtype: 'treepicker',  
                //本地数据源  local/remote  
                displayField: "text",         
                //设置为选项的value的字段   
                //是否可以输入，还是只能选择下拉框中的选项  
                //selectOnFocus:true,  
                //数据  
                store:tree_store
            }, {  
                fieldLabel: '日历控件',  
                xtype: 'datefield',  
                name: 'DateControl',  
                format: "Y-m-d",  
                editable : false  
                //, 默认当前日期  
                //value:new Date().dateFormat('Y-m-d')  
            },{  
                fieldLabel: '单选控件'  
                ,xtype:'radiogroup'  
                ,name:'Radios'  
                ,items:[  
                    {name : 'RadioItems',boxLabel:'选我',inputValue:'1',checked:true},  
                    {name : 'RadioItems',boxLabel:'选我吧',inputValue:'0'}  
                ]  
            },{  
                fieldLabel: '复选控件'  
                ,xtype:'checkboxgroup'  
                ,name:'Checkboxs'  
                //columns属性表示用2行来显示数据  
                ,columns:2  
                ,items:[  
                    {name : 'CheckboxItems',boxLabel:'香蕉',inputValue:'A'},  
                    {name : 'CheckboxItems',boxLabel:'苹果',inputValue:'B'},  
                    {name : 'CheckboxItems',boxLabel:'橘子',inputValue:'C'},  
                    {name : 'CheckboxItems',boxLabel:'桃子',inputValue:'D'}  
                ]  
            },{  
                fieldLabel: '文本域控件'  
                ,xtype:'textarea'  
                ,value:'可以输好多字！'  
                ,height:50  
            },{  
                fieldLabel: '时间控件'  
                ,xtype:'timefield'  
                //格式化输出 默认为 "g:i A"  
                //"g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H"  
                ,format:'H:i'  
                //时间间隔(分钟)  
                ,increment: 60  
            },{  
                fieldLabel: '标签页'  
                ,xtype:'fieldset'  
                ,title: '标签页'  
                ,autoHeight:true  
                ,items :[{  
                    xtype: 'panel',  
                    title: '标签页中的面板',  
                    frame: true,  
                    height: 50  
                }]  
            },{  
                fieldLabel: '在线编辑器'  
                ,xtype:'htmleditor'  
                ,width:360  
                ,height:100  
                //以下为默认选项，其他请参照源代码  
                //,enableColors: false  
                //,enableFormat : true  
                //,enableFontSize : true  
                //,enableAlignments : true  
                //,enableLists : true  
                //,enableSourceEdit : true  
                //,enableLinks : true  
                //,enableFont : true  
            }],  
            buttons: [{  
                text: "保 存"  
                ,handler:function(){  
                    MsgInfo('保存');  
                }  
            }, {  
                text: "取 消"  
                ,handler:function(){  
                    form1.form.reset();  
                }  
            }]  
        });  
  
        function MsgInfo(str_msg)  
        {  
            Ext.MessageBox.show({  
                title: '提示',  
                msg: str_msg,  
                icon:Ext.MessageBox.INFO,  
                buttons: Ext.MessageBox.OK  
            });  
        }  
    });  

